package p2p;

import java.net.DatagramPacket;

/** Thread that "listens" to the data port.
 * @author Bruno
 */
public class DataPortThread extends Thread {

	@Override
	public void run() {
		listenDataPort();
	}

	private void listenDataPort() {
        DatagramPacket packet;
		byte[] buffer;

		// Continuously receive packets
		while(true) {
			// Receive the packet
			buffer = new byte[bufferSize];
            packet = new DatagramPacket(buffer, buffer.length);
			try {
				Global.dataSocket.receive(packet);

				// Convert to NetworkChunk
				NetworkChunk netChunk = new NetworkChunk(buffer);

				String hash = netChunk.getHash();
				P2PFile file = P2PFileList.getFileByHash(hash);
				
				if(file != null && file.getState() != P2PFile.STATE_PAUSED) { // Do "I" have the file?
					int chunkNumber = netChunk.getChunkNumber();
					if(file.isChunkAvailable(chunkNumber)) { // Do "I" have that chunk already?
						file.removeRequestedChunk(chunkNumber); // Someone else has just sent a chunk that was requested
					}
					else {
						// Add the chunk to the file's received chunks to be processed later
						file.addReceivedChunk(netChunk);
					}
				}
			} catch (Exception ex) {
				// Ignore
			}
		}
	}

	static final private int bufferSize = 2 * 32 + Global.chunkSize;
}
